package cn.gzjp.modules.logis.web;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import cn.gzjp.modules.logis.entity.LogisDelivery;
import cn.gzjp.modules.logis.entity.LogisDeliveryLog;
import cn.gzjp.modules.logis.entity.LogisMessage;
import cn.gzjp.modules.logis.service.*;
import cn.hutool.core.util.StrUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisInsurePhoto;

/**
 * 货运保险Controller
 * @author zengcp
 * @version 2018-04-28
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisInsurePhoto")
public class LogisInsurePhotoController extends BaseController {

	@Autowired
	private LogisInsurePhotoService logisInsurePhotoService;
	@Autowired
	private LogisDeliveryService logisDeliveryService;
	@Autowired
	private LogisMessageService logisMessageService;
	@Autowired
	private LogisDeliveryLogService logisDeliveryLogService;
	@Autowired
	private LogisCarService logisCarService;
	
	
	/**
	 * 货运保险列表页面
	 */
	@RequiresPermissions("logis:logisInsurePhoto:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisInsurePhoto logisInsurePhoto, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisInsurePhoto> page = logisInsurePhotoService.findPage(new Page<LogisInsurePhoto>(request, response), logisInsurePhoto); 
		model.addAttribute("page", page);
		return "modules/logis/logisInsurePhotoList";
	}

	/**
	 * 查看，增加，编辑货运保险表单页面
	 */
	@RequiresPermissions(value={"logis:logisInsurePhoto:view","logis:logisInsurePhoto:add","logis:logisInsurePhoto:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisInsurePhoto logisInsurePhoto, Model model) {
		model.addAttribute("logisInsurePhoto", logisInsurePhoto);
		LogisDelivery delivery = logisDeliveryService.get(logisInsurePhoto.getId());
		model.addAttribute("delivery",delivery);
		if(delivery!=null&& StrUtil.isNotBlank(delivery.getCarOpenid())){
			model.addAttribute("driver",logisCarService.get(delivery.getCarOpenid()));
		}

		return "modules/logis/logisInsurePhotoForm";
	}

	/**
	 * 保存货运保险
	 */
	@RequiresPermissions(value={"logis:logisInsurePhoto:add","logis:logisInsurePhoto:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisInsurePhoto logisInsurePhoto, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisInsurePhoto)){
			return form(logisInsurePhoto, model);
		}
		if(!logisInsurePhoto.getIsNewRecord()){//编辑表单保存
			LogisInsurePhoto t = logisInsurePhotoService.get(logisInsurePhoto.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisInsurePhoto, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisInsurePhotoService.save(t);//保存
			LogisDelivery order = this.logisDeliveryService.get(logisInsurePhoto.getId());
			order.setInsuranceStatus(2);
			logisDeliveryService.save(order);

//			private String status2;//2.受益人信息 审核状态
//			private String status3;//3.货物装车照片 审核状态
//			private String status4;//4.货车手续  审核状态
//			private String status5;//5.发货单 审核结果

			if("2".equals(t.getStatus2())){
				LogisMessage message = new LogisMessage();
				message.setOpenid(order.getReceiver());
				message.setType("1");
				message.setStatus(0);
				message.setContent("受益人信息审核驳回 :"+t.getRefusereason2());
				message.setDeliveryId(order.getId());
				logisMessageService.save(message);
			}
			if("2".equals(t.getStatus3())){
				LogisMessage message = new LogisMessage();
				message.setOpenid(order.getCarrier());
				message.setType("1");
				message.setStatus(0);
				message.setContent("货物装车照片审核驳回 :"+t.getRefusereason3());
				message.setDeliveryId(order.getId());
				logisMessageService.save(message);
			}
			if("2".equals(t.getStatus4())){
				LogisMessage message = new LogisMessage();
				message.setOpenid(order.getCarrier());
				message.setType("1");
				message.setStatus(0);
				message.setContent("货车手续信息审核驳回 :"+t.getRefusereason4());
				message.setDeliveryId(order.getId());
				logisMessageService.save(message);
			}
			if("2".equals(t.getStatus5())){
				LogisMessage message = new LogisMessage();
				message.setOpenid(order.getCarrier());
				message.setType("1");
				message.setStatus(0);
				message.setContent("发货单信息审核驳回 :"+t.getRefusereason5());
				message.setDeliveryId(order.getId());
				logisMessageService.save(message);
			}
			if("1".equals(t.getStatus())){
				LogisDelivery delivery = order;
				if (delivery != null) {
					delivery.setInsurStatus("43");
					delivery.setCarrierStatus("33");
					logisDeliveryService.save(delivery);
					LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
					deliveryLog.setOpenid("admin");
					deliveryLog.setDeliveryId(delivery.getId());
					deliveryLog.setStatus("43");
					deliveryLog.setType("4");
					logisDeliveryLogService.save(deliveryLog);
				}

			}
		}else{//新增表单保存
			logisInsurePhotoService.save(logisInsurePhoto);//保存
		}
		addMessage(redirectAttributes, "保存货运保险成功");
		return redirect("/logis/logisInsurePhoto/?repage");
	}
	
	/**
	 * 删除货运保险
	 */
	@RequiresPermissions("logis:logisInsurePhoto:del")
	@RequestMapping(value = "delete")
	public String delete(LogisInsurePhoto logisInsurePhoto, RedirectAttributes redirectAttributes) {
		logisInsurePhotoService.delete(logisInsurePhoto);
		addMessage(redirectAttributes, "删除货运保险成功");
		return redirect("/logis/logisInsurePhoto/?repage");
	}
	
	/**
	 * 批量删除货运保险
	 */
	@RequiresPermissions("logis:logisInsurePhoto:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisInsurePhotoService.delete(logisInsurePhotoService.get(id));
		}
		addMessage(redirectAttributes, "删除货运保险成功");
		return redirect("/logis/logisInsurePhoto/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisInsurePhoto:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisInsurePhoto logisInsurePhoto, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "货运保险"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisInsurePhoto> page = logisInsurePhotoService.findPage(new Page<LogisInsurePhoto>(request, response, -1), logisInsurePhoto);
    		new ExportExcel("货运保险", LogisInsurePhoto.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出货运保险记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisInsurePhoto/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisInsurePhoto:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisInsurePhoto> list = ei.getDataList(LogisInsurePhoto.class);
			for (LogisInsurePhoto logisInsurePhoto : list){
				try{
					logisInsurePhotoService.save(logisInsurePhoto);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条货运保险记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条货运保险记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入货运保险失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisInsurePhoto/?repage");
    }
	
	/**
	 * 下载导入货运保险数据模板
	 */
	@RequiresPermissions("logis:logisInsurePhoto:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "货运保险数据导入模板.xlsx";
    		List<LogisInsurePhoto> list = Lists.newArrayList(); 
    		new ExportExcel("货运保险数据", LogisInsurePhoto.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisInsurePhoto/?repage");
    }
	@ModelAttribute
	public LogisInsurePhoto get(@RequestParam(required=false) String id) {
		LogisInsurePhoto entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisInsurePhotoService.get(id);
		}
		if (entity == null){
			entity = new LogisInsurePhoto();
		}
		return entity;
	}

	@RequestMapping(value = "download")
	public void downPicture(HttpServletRequest request,HttpServletResponse response,String id) throws Exception, IOException {
		LogisInsurePhoto entity = logisInsurePhotoService.get(id);

		ServletContext sc = request.getSession().getServletContext();
		String curWebAppRoot = sc.getRealPath("/");



		String picUrl = curWebAppRoot+entity.getPic1();
		File file = new File(picUrl);
		//将图片读成二进制流
		FileImageInputStream fs = new FileImageInputStream (file);
		int streamLength = (int)fs.length();
		byte[] image = new byte[streamLength ];
		fs.read(image,0,streamLength );
		fs.close();
		response.addHeader("Content-Type","application/octet-stream");
		response.addHeader("Content-Disposition","attachment;filename="+id+".jpg");
		response.getOutputStream().write(image );
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
	

}